# frozen_string_literal: true

class RuleEntity
  class DecisionTable < RuleEntity
    has_many :decision_table_headers, foreign_key: :decision_table_id, dependent: :delete_all
    has_many :decision_table_rows, foreign_key: :decision_table_id, dependent: :destroy

    has_many :input_headers, through: :input_variables, class_name: 'DecisionTableHeader'
    has_many :output_headers, through: :output_variables, class_name: 'DecisionTableHeader'

    def build_archive_params
      raise 'Unsupported.'
    end

    def update_draft(_params)
      raise 'Unsupported'
    end

    # rubocop:disable Metrics/AbcSize
    def fire_without_validate(params)
      cells = decision_table_rows

      output_columns = ['decision_table_rows.ordinal AS ordinal']

      schema_variables.includes(decision_table_headers: { schema_variable: :variable_type })
      schema_variables.each do |variable|
        input_value = params[variable.name] if variable.io_type.eql?(SchemaVariable::IoType::INPUT)

        variable.decision_table_headers.each do |header|
          tb_name = "tb_column_#{header.ordinal}"

          cells = cells.joins("INNER JOIN `decision_table_cells` AS #{tb_name} " \
            "ON `decision_table_rows`.`id`=#{tb_name}.`decision_table_row_id` " \
            "AND #{tb_name}.`ordinal`=#{header.ordinal}")

          col_name = DecisionTableService.dt_column_name_by_header(header)
          if input_value
            cells = cells.where("? #{header.type_method.name} #{tb_name}.`#{col_name}`", input_value)
          else
            output_columns << "`#{tb_name}`.`#{col_name}` AS #{variable.name}"
          end
        end
      end
      cells = cells.ordinal_asc.limit(1) if policy.eql?(Policy::FIRST)
      cells.select(output_columns).as_json(except: :id)
    end
    # rubocop:enable Metrics/AbcSize
  end
end
